package com.laiketui.common.service.dubbo.plugin.integral;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Maps;
import com.laiketui.common.annotation.HandlerOrderType;
import com.laiketui.common.api.PublicAddressService;
import com.laiketui.common.api.PublicOrderService;
import com.laiketui.common.api.PublicStockService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.order.OrderDubboService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.GoodsDataUtils;
import com.laiketui.common.utils.tool.data.OrderDataUtils;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.domain.config.ConfiGureModel;
import com.laiketui.domain.config.IntegralConfigModel;
import com.laiketui.domain.distribution.FreightModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.mch.IntegralGoodsModel;
import com.laiketui.domain.mch.MchBrowseModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.message.MessageLoggingModal;
import com.laiketui.domain.order.OrderDetailsModel;
import com.laiketui.domain.order.OrderModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.user.UserAddress;
import com.laiketui.domain.vo.OrderVo;
import com.laiketui.domain.vo.goods.AddStockVo;
import com.laiketui.domain.vo.order.*;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 积分订单流程
 *
 * @author Trick
 * @date 2021/4/14 14:19
 */
@HandlerOrderType(type = DictionaryConst.OrdersType.ORDERS_HEADER_IN)
@Service
public class IntegralOrderServiceImpl implements OrderDubboService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IntegralGoodsModelMapper integralGoodsModelMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private PublicAddressService publicAddressService;

    @Autowired
    private PublicOrderService publicOrderService;

    @Autowired
    private ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    private MchBrowseModelMapper mchBrowseModelMapper;

    @Autowired
    private PublicStockService publicStockService;

    @Autowired
    private IntegralConfigModelMapper integralConfigModelMapper;

    @Autowired
    private PaymentConfigModelMapper paymentConfigModelMapper;

    @Autowired
    private FreightModelMapper freightModelMapper;

    @Autowired
    private SignRecordModelMapper signRecordModelMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MessageLoggingModalMapper messageLoggingModalMapper;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Override
    public Map<String, Object> settlement(OrderVo vo) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            user = userMapper.selectByPrimaryKey(user.getId());
            //总价
            BigDecimal money = new BigDecimal("0");
            //是否能支付
            boolean isPay = true;
            //是否设置支付密码
            int pwdStatus = DictionaryConst.WhetherMaven.WHETHER_OK;
            if (user.getLogin_num().equals(GloabConst.LktConfig.LOGIN_AGAIN_MAX)) {
                isPay = false;
            }
            if (StringUtils.isEmpty(user.getPassword())) {
                pwdStatus = DictionaryConst.WhetherMaven.WHETHER_NO;
            }
            List<Map<String, Object>> productList;
            try {
                productList = JSON.parseObject(vo.getProductsInfo(), new TypeReference<List<Map<String, Object>>>() {
                });
            } catch (JSONException j) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSGSBZQ, vo.getProductsInfo() + ">参数格式不正确", "immediatelyCart");
            }
            if (productList == null || productList.size() == 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSBZQ, "参数不正确");
            }
            //获取商品规格信息
            int attrId = 0;
            //所需数量
            int needNum = 0;
            //商品id
            int pid = 0;
            for (Map<String, Object> attrMap : productList) {
                if (attrMap.containsKey("cid")) {
                    attrId = MapUtils.getIntValue(attrMap, "cid");
                } else if (attrMap.containsKey("num")) {
                    needNum = MapUtils.getIntValue(attrMap, "num");
                }else if (attrMap.containsKey("pid")){
                    pid = MapUtils.getIntValue(attrMap, "pid");
                }
            }
            //获取用户地址
            UserAddress userAddress = publicAddressService.findAddress(vo.getStoreId(), user.getUser_id(), vo.getAddressId());
            //获取商品信息
            if (pid == 0){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "商品pid不存在");
            }
            Map<String, Object> goodsDetailInfo = integralGoodsModelMapper.getGoodsDetailInfo(pid, attrId);
            if (goodsDetailInfo == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在");
            }
            if (MapUtils.getInteger(goodsDetailInfo, "num") < needNum) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KCBZ, "库存不足");
            }
            //修正积分商品id
            vo.setMainId(MapUtils.getInteger(goodsDetailInfo, "id"));
            //获取店铺信息
            Map<String, Object> shopInfo = new HashMap<>(16);
            Integer mchId = StringUtils.stringParseInt(goodsDetailInfo.get("mch_id"));
            if (mchId != null) {
                MchModel mchModel = mchModelMapper.selectByPrimaryKey(mchId);
                if (mchModel != null) {
                    shopInfo.putAll(publiceService.commodityInformation(vo.getStoreId(), mchId));
                    shopInfo.put("mch_id", mchId);
                    shopInfo.put("shop_name", mchModel.getName());
                    shopInfo.put("shop_logo", publiceService.getImgPath(mchModel.getLogo(), vo.getStoreId()));
                }
            }
            goodsDetailInfo.putAll(shopInfo);

            ConfiGureModel confiGureModel = new ConfiGureModel();
            confiGureModel.setId(attrId);
            confiGureModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS.toString());
            confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
            if (confiGureModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPGGBCZ, "商品规格不存在");
            }
            goodsDetailInfo.put("imgurl", publiceService.getImgPath(confiGureModel.getImg(), vo.getStoreId()));
            goodsDetailInfo.put("size", GoodsDataUtils.getProductSkuValue(confiGureModel.getAttribute()));
            //获取所需价格
            BigDecimal goodsPrice = new BigDecimal(MapUtils.getString(goodsDetailInfo, "money"));
            //所需积分
            BigDecimal integral = new BigDecimal(MapUtils.getString(goodsDetailInfo, "integral")).multiply(new BigDecimal(needNum));

            BigDecimal zl = new BigDecimal(MapUtils.getString(goodsDetailInfo, "weight"));

            //计算价格
            BigDecimal freightPrice = this.getFreight(vo.getStoreId(), null, needNum, StringUtils.stringParseInt(goodsDetailInfo.get("freight").toString()), userAddress, zl);
            money = money.add(goodsPrice).multiply(BigDecimal.valueOf(needNum));
            goodsDetailInfo.put("num", needNum);


            //各个支付的开启、关闭状态
            Map<String, Object> map = new HashMap<>();
            map.put("store_id", vo.getStoreId());
            List<Map<String, Object>> paymentStatus = paymentConfigModelMapper.getPaymentConfigDynamic(map);
            Map<String, Integer> payment = Maps.newHashMap();
            for (Map<String, Object> paymentConf : paymentStatus) {
                int isOpen = DataUtils.getIntegerVal(paymentConf, "statusSwitch", 0);
                payment.put(DataUtils.getStringVal(paymentConf, "class_name"), isOpen);
            }
            resultMap.put("payment", payment);

            resultMap.put("money", money);
            resultMap.put("total", money.add(freightPrice));
            resultMap.put("integral", integral);
            resultMap.put("freight", freightPrice);
            resultMap.put("enterless", isPay);
            resultMap.put("address", userAddress);
            resultMap.put("products", goodsDetailInfo);
            resultMap.put("user_money", user.getMoney());
            resultMap.put("user_score", user.getScore());
            resultMap.put("password_status", pwdStatus);
            resultMap.put("addemt", userAddress != null ? 1 : 0);
        } catch (LaiKeAPIException l) {
            logger.error("积分兑换-结算 异常", l);
            throw l;
        } catch (Exception e) {
            logger.error("积分兑换-结算 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "settlement");
        }
        return resultMap;
    }


    /**
     * 计算秒杀运费
     *
     * @param storeId     -
     * @param mchId       - 店铺id
     * @param num         - 购买的数量
     * @param freightId   - 运费模板id
     * @param userAddress - 用户收货地址
     * @return BigDecimal
     * @throws LaiKeAPIException-
     * @author Trick
     * @date 2021/10/21 15:06
     */
    private BigDecimal getFreight(int storeId, Integer mchId, Integer num, Integer freightId,
                                  UserAddress userAddress, BigDecimal weightNum) throws LaiKeAPIException {
        //运费
        BigDecimal freightPrice = BigDecimal.ZERO;
        try {
            if (mchId == null){
                //获取自营店id
                mchId = customerModelMapper.getStoreMchId(storeId);
            }
            //是否开启了包邮设置
            int packageSettings = DictionaryConst.WhetherMaven.WHETHER_NO;
            //同件
            int samePiece = 0;
            IntegralConfigModel integralConfigModel = new IntegralConfigModel();
            integralConfigModel.setStore_id(storeId);
            integralConfigModel.setMch_id(mchId);
            integralConfigModel = integralConfigModelMapper.selectOne(integralConfigModel);
            if (integralConfigModel != null) {
                packageSettings = integralConfigModel.getPackage_settings();
                if (packageSettings == DictionaryConst.WhetherMaven.WHETHER_OK) {
                    samePiece = integralConfigModel.getSame_piece();
                }
            }
            //是否免邮
            boolean orderFreight = false;
            //是否开启包邮设置
            if (packageSettings == DictionaryConst.WhetherMaven.WHETHER_OK) {
                //是否满足同件免邮规则
                orderFreight = samePiece <= num;
            }
            if (orderFreight) {
                //满足免邮条件
                return freightPrice;
            } else {
                FreightModel freightModel = new FreightModel();
                if (freightId != null) {
                    //根据运费模版id
                    freightModel.setId(freightId);
                } else {
                    //如果没有默认模板则获取默认模板
                    freightModel.setStore_id(storeId);
                    freightModel.setMch_id(mchId);
                    freightModel.setIs_default(DictionaryConst.DefaultMaven.DEFAULT_OK);
                }
                //运费信息
                freightModel = freightModelMapper.selectOne(freightModel);
                if (freightModel != null) {
                    //获取运费
                    BigDecimal goodsYunFei = publicOrderService.getFreight(freightModel.getId(), userAddress, num, weightNum);
                    //计算总运费
                    freightPrice = freightPrice.add(goodsYunFei);
                }
            }

        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("计算秒杀运费 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPXXBWZ, "商品信息不完整", "getFreight");
        }
        return freightPrice;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> payment(OrderVo vo) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //刷新缓存
            user = userBaseMapper.selectByPrimaryKey(user.getId());
            RedisDataTool.refreshRedisUserCache(vo.getAccessId(), user, redisUtil);

            List<Map<String, Object>> productList;
            try {
                productList = JSON.parseObject(vo.getProductsInfo(), new TypeReference<List<Map<String, Object>>>() {
                });
            } catch (JSONException j) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSGSBZQ, vo.getProductsInfo() + ">参数格式不正确", "payment");
            }
            if (vo.getMainId() == null || productList == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            //商品id
            int goodsId = 0;
            //获取商品规格信息
            int attrId = 0;
            //所需数量
            int needNum = 0;
            for (Map<String, Object> attrMap : productList) {
                if (attrMap.containsKey("pid")) {
                    goodsId = MapUtils.getIntValue(attrMap, "pid");
                } else if (attrMap.containsKey("cid")) {
                    attrId = MapUtils.getIntValue(attrMap, "cid");
                } else if (attrMap.containsKey("num")) {
                    needNum = MapUtils.getIntValue(attrMap, "num");
                }
            }

            //获取积分商品信息
            IntegralGoodsModel integralGoodsOld = new IntegralGoodsModel();
            integralGoodsOld.setStore_id(vo.getStoreId());
            integralGoodsOld.setAttr_id(attrId);
            integralGoodsOld.setGoods_id(goodsId);
            integralGoodsOld.setIs_delete(DictionaryConst.ProductRecycle.NOT_STATUS);
            integralGoodsOld = integralGoodsModelMapper.selectOne(integralGoodsOld);
            if (integralGoodsOld == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JFSPBCZ, "积分商品不存在");
            }
            //修正积分商品id
            vo.setMainId(integralGoodsOld.getId());
            //获取商品信息
            ProductListModel productListOld = new ProductListModel();
            productListOld.setId(goodsId);
            productListOld.setStore_id(vo.getStoreId());
            productListOld.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS.toString());
            productListOld = productListModelMapper.selectOne(productListOld);
            if (productListOld == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在");
            }
            BigDecimal zl = new BigDecimal(productListOld.getWeight());

            //获取用户地址
            UserAddress userAddress = publicAddressService.findAddress(vo.getStoreId(), user.getUser_id(), vo.getAddressId());
            BigDecimal freightPrice = this.getFreight(vo.getStoreId(), null, needNum, Integer.parseInt(productListOld.getFreight()), userAddress, zl);
            // 订单备注
            Map<String, String> mchRemarks = new HashMap<>();
            if (!StringUtils.isEmpty(vo.getRemarks())) {
                mchRemarks.put(productListOld.getMch_id().toString(), vo.getRemarks());
            }

            FreightModel freightModel = freightModelMapper.selectByPrimaryKey(productListOld.getFreight());
            if (freightModel != null) {
                //用户地址 省-市-区对应运费模板里的格式
                String address = userAddress.getSheng() + "-" + userAddress.getCity() + "-" + userAddress.getQuyu();
                //不配送区域参数列表
                String bpsRule = URLDecoder.decode(freightModel.getNo_delivery(), CharEncoding.UTF_8);
                JSONArray objects = JSONArray.parseArray(bpsRule);
                if (objects.contains(address)) {
                    logger.debug("地址超出配送范围");
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DZCCPSFW, "地址超出配送范围", "getNo_delivery");
                }
            }
            //商品名称
            String goodsName = productListOld.getProduct_title();
            //所需金额(原价)
            BigDecimal needMoney = integralGoodsOld.getMoney();
            //所需积分
            BigDecimal needScore = new BigDecimal(integralGoodsOld.getIntegral()).multiply(new BigDecimal(needNum));
            //获取规格信息
            ConfiGureModel attrOld = confiGureModelMapper.selectByPrimaryKey(attrId);
            //规格处理
            String attribute = GoodsDataUtils.getProductSkuValue(attrOld.getAttribute());

            //获取用户信息
            user = userBaseMapper.selectByPrimaryKey(user.getId());
            if (vo.getPayType().equals(DictionaryConst.OrderPayType.ORDERPAYTYPE_WALLET_PAY) &&
                    user.getMoney().compareTo(needMoney.multiply(new BigDecimal(needNum))) < 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YEBZ, "余额不足");
            } else if (user.getScore() < needScore.intValue()) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JFBZ, "积分不足");
            } else if (integralGoodsOld.getNum() - needNum < 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KCBZ, "库存不足");
            }
            //添加一条购买记录
            MchBrowseModel mchBrowseModel = new MchBrowseModel();
            mchBrowseModel.setMch_id(productListOld.getMch_id().toString());
            mchBrowseModel.setStore_id(vo.getStoreId());
            mchBrowseModel.setUser_id(user.getUser_id());
            mchBrowseModel.setEvent("购买了积分商品");
            mchBrowseModel.setAdd_time(new Date());
            mchBrowseModelMapper.insertSelective(mchBrowseModel);
            //添加积分商品以扣减库存-无需重复出库
            //出库
//            publicStockService.outStockNum(vo.getStoreId(), productListOld.getId(), attrId, needNum);
            //生成订单号
            String orderNo = publicOrderService.createOrderNo(DictionaryConst.OrdersType.ORDERS_HEADER_IN);
            // 生成支付订单号
            String realSno = publicOrderService.createOrderNo(DictionaryConst.OrdersType.ORDERS_HEADER_IN);
            //生成订单明细
            OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
            orderDetailsModel.setStore_id(vo.getStoreId());
            orderDetailsModel.setUser_id(user.getUser_id());
            //积分商品id
            orderDetailsModel.setP_id(vo.getMainId());
            orderDetailsModel.setP_name(goodsName);
            orderDetailsModel.setP_price(needMoney);
            orderDetailsModel.setNum(needNum);
            orderDetailsModel.setUnit(attrOld.getUnit());
            orderDetailsModel.setR_sNo(orderNo);
            orderDetailsModel.setAdd_time(new Date());
            orderDetailsModel.setR_status(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID);
            orderDetailsModel.setSize(attribute);
            orderDetailsModel.setSid(attrId + "");
            orderDetailsModel.setFreight(freightPrice);
            orderDetailsModel.setSettlement_type(OrderDetailsModel.SETTLEMENT_TYPE_UNSETTLED);
            orderDetailsModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            //消费积分记录在这里
            orderDetailsModel.setAfter_discount(new BigDecimal(integralGoodsOld.getIntegral()));
            int row = orderDetailsModelMapper.insertSelective(orderDetailsModel);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSBQSHZS, "下单失败,请稍后再试");
            }
            //获取订单配置
            Map<String, Object> configMap = publicOrderService.getOrderConfig(vo.getStoreId(), productListOld.getMch_id(), DictionaryConst.OrdersType.ORDERS_HEADER_IN);
            //订单失效  - 秒
            Integer orderFailureDay = 3600;
            if (StringUtils.isNotEmpty(configMap)){
                //未付款订单保留时间
                orderFailureDay = MapUtils.getInteger(configMap, "orderFailureDay");
                if (orderFailureDay == null || orderFailureDay < 0){
                    orderFailureDay = 3600;
                }
            }
            OrderModel orderModel = new OrderModel();
            orderModel.setStore_id(vo.getStoreId());
            orderModel.setUser_id(user.getUser_id());
            orderModel.setName(userAddress.getName());
            orderModel.setMobile(userAddress.getTel());
            orderModel.setNum(needNum);
            orderModel.setZ_price(needMoney.multiply(new BigDecimal(needNum)).add(freightPrice));
            orderModel.setOld_total(orderModel.getZ_price());
            orderModel.setsNo(orderNo);
            orderModel.setReal_sno(realSno);
            orderModel.setRemark(vo.getRemarks());
            orderModel.setSheng(userAddress.getSheng());
            orderModel.setShi(userAddress.getCity());
            orderModel.setXian(userAddress.getQuyu());
            orderModel.setAddress(userAddress.getAddress());
            orderModel.setSpz_price(needScore);
            orderModel.setStatus(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID);
            orderModel.setSource(vo.getStoreType());
            orderModel.setOtype(DictionaryConst.OrdersType.ORDERS_HEADER_IN);
            orderModel.setMch_id(String.format("%s%s%s", SplitUtils.DH, productListOld.getMch_id(), SplitUtils.DH));
            orderModel.setP_sNo(vo.getMainId() + "");
            orderModel.setRemarks(JSON.toJSONString(mchRemarks));
            orderModel.setZ_freight(freightPrice);
            orderModel.setAllow(needScore.intValue());
            orderModel.setSubtraction_id(0);
            orderModel.setAdd_time(new Date());
            orderModel.setOrderFailureTime(orderFailureDay);
            row = orderModelMapper.insertSelective(orderModel);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSBQSHZS, "下单失败,请稍后再试");
            }
            //扣减库存
            row = integralGoodsModelMapper.addStockNum(integralGoodsOld.getId(), -needNum);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JFSPKCBZ, "积分商品库存不足");
            }

            MessageLoggingModal messageLoggingSave = new MessageLoggingModal();
            messageLoggingSave.setMch_id(productListOld.getMch_id());
            messageLoggingSave.setStore_id(vo.getStoreId());
            messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_ORDER_NEW);
            messageLoggingSave.setTo_url(OrderDataUtils.getOrderRoute(DictionaryConst.OrdersType.ORDERS_HEADER_IN, 0));
            messageLoggingSave.setParameter(orderModel.getId() + "");
            messageLoggingSave.setContent(String.format("您来新订单了，订单为%s，请及时处理！", orderModel.getsNo()));
            messageLoggingSave.setAdd_date(new Date());
            messageLoggingModalMapper.insertSelective(messageLoggingSave);

            resultMap.put("sNo", orderNo);
            resultMap.put("total", orderModel.getZ_price());
            resultMap.put("total_score", orderModel.getAllow());
            resultMap.put("order_id", orderModel.getId());
            //下单时间
            resultMap.put("orderTime", DateUtil.dateFormate(orderModel.getAdd_time(), GloabConst.TimePattern.YMDHMS));
        } catch (LaiKeAPIException e) {
            logger.error("积分商城兑换下单 异常", e);
            throw e;
        } catch (Exception e) {
            logger.error("积分商城兑换下单 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "payment");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> updateOrderRemark(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> splitOrder(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> returnData(ApplyReturnDataVo vo, MultipartFile file) throws LaiKeAPIException {
        return null;
    }

    @Override
    public Map<String, Object> orderList(OrderVo vo) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);

            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("storeId", vo.getStoreId());
            parmaMap.put("userId", user.getUser_id());
            parmaMap.put("orderType", vo.getQueryOrderType());
            parmaMap.put("start", vo.getPageNo());
            if (vo.getMchId() != null && user.getMchId() != null) {
                if (user.getMchId().equals(vo.getMchId())) {
                    parmaMap.put("mchId", user.getMchId());
                }
            }
            parmaMap.put("keyWord", vo.getKeyword());
            parmaMap.put("pageSize", vo.getPageSize());
            parmaMap.put("otype", DictionaryConst.OrdersType.ORDERS_HEADER_IN);
            //禅道49609 -》用户、商家、平台删除自己的订单
            parmaMap.put("userRecycle", OrderModel.SHOW);
            List<Map<String, Object>> orderList = orderModelMapper.getUserCenterOrderList(parmaMap);
            for (Map<String, Object> orderInfo : orderList) {
                //总运费
                BigDecimal totalYunFei = BigDecimal.ZERO;
                //商品总数量
                BigDecimal totalNeedNum = BigDecimal.ZERO;
                //订单号
                String orderno = orderInfo.get("sNo").toString();
                //店铺id
                int mchId = 0;
                // 店铺 名称
                String mchName = "";
                // 店铺logo
                String logoUrl = "";

                //店铺信息处理
                String mchIdStr = orderInfo.get("mch_id") + "";
                if (!StringUtils.isEmpty(mchIdStr)) {
                    mchId = Integer.parseInt(StringUtils.trim(mchIdStr, SplitUtils.DH));
                    //获取店铺信息
                    MchModel mchModel = mchModelMapper.selectByPrimaryKey(mchId);
                    mchName = mchModel.getName();
                    logoUrl = publiceService.getImgPath(mchModel.getLogo(), vo.getStoreId());
                }
                orderInfo.put("shop_id", mchId);
                orderInfo.put("shop_name", mchName);
                orderInfo.put("shop_logo", logoUrl);

                //获取订单明细
                OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
                orderDetailsModel.setStore_id(vo.getStoreId());
                orderDetailsModel.setR_sNo(orderno);
                List<OrderDetailsModel> detailList = orderDetailsModelMapper.select(orderDetailsModel);
                List<Map<String, Object>> orderDetailsModelList = JSON.parseObject(JSON.toJSONString(detailList), new TypeReference<List<Map<String, Object>>>() {
                });
                for (Map<String, Object> orderDetails : orderDetailsModelList) {
                    //统计运费
                    totalYunFei = totalYunFei.add(new BigDecimal(orderDetails.get("freight").toString()));
                    totalNeedNum = totalNeedNum.add(new BigDecimal(orderDetails.get("num").toString()));
                    int attrId = Integer.parseInt(orderDetails.get("sid").toString());
                    ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(attrId);
                    if (confiGureModel == null) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJCW, "数据错误");
                    }
                    int goodsId = confiGureModel.getPid();
                    orderDetails.put("pro_id", goodsId);
                    orderDetails.put("imgurl", publiceService.getImgPath(confiGureModel.getImg(), vo.getStoreId()));
                    orderDetails.put("comments_type", publicOrderService.orderCommentType(vo.getStoreId(), user.getUser_id(),
                            orderno, MapUtils.getIntValue(orderDetails, "id"), MapUtils.getIntValue(orderDetails, "sid"), MapUtils.getIntValue(orderDetails, "r_status")));
                }
                orderInfo.put("refund", true);
                orderInfo.put("list", orderDetailsModelList);
                orderInfo.put("z_freight", totalYunFei);
                orderInfo.put("sum", totalNeedNum);
            }
            resultMap.put("order", orderList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("积分订单列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "orderList");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> remindDelivery(OrderVo vo) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> cancleOrder(OrderVo vo) {
        try {
            OrderModel orderOld = new OrderModel();
            orderOld.setId(vo.getOrderId());
            orderOld.setStore_id(vo.getStoreId());
            orderOld.setOtype(DictionaryConst.OrdersType.ORDERS_HEADER_IN);
            orderOld.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
            orderOld = orderModelMapper.selectOne(orderOld);
            if (orderOld == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDBCZ, "订单不存在");
            }
            if (!orderOld.getStatus().equals(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDBZDFKZT, "订单不在待付款状态");
            }
            //关闭订单
            OrderModel orderUpdate = new OrderModel();
            orderUpdate.setId(orderOld.getId());
            orderUpdate.setStatus(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CLOSE);
            int row = orderModelMapper.updateByPrimaryKeySelective(orderUpdate);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDGBSB, "订单关闭失败");
            }
            //关闭明细
            row = orderDetailsModelMapper.closeOrder(orderOld.getsNo());
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDGBSB, "订单关闭失败");
            }
            //获取订单明细
            OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
            orderDetailsModel.setStore_id(vo.getStoreId());
            orderDetailsModel.setR_sNo(orderOld.getsNo());
            orderDetailsModel.setP_id(vo.getMainId());
            orderDetailsModel = orderDetailsModelMapper.selectOne(orderDetailsModel);
            if (orderDetailsModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDSJCW, "订单数据错误");
            }
            //获取插件商品
            IntegralGoodsModel integralGoodsModel = integralGoodsModelMapper.selectByPrimaryKey(orderDetailsModel.getP_id());
            if (integralGoodsModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在");
            }
            //回滚库存
            integralGoodsModelMapper.releaseStockNum(orderOld.getsNo(), integralGoodsModel.getId());

            //回滚商品库存
            AddStockVo addStockVo = new AddStockVo();
            addStockVo.setStoreId(vo.getStoreId());
            addStockVo.setId(Integer.parseInt(orderDetailsModel.getSid()));
            addStockVo.setPid(integralGoodsModel.getGoods_id());
            addStockVo.setAddNum(orderDetailsModel.getNum());
            addStockVo.setText(orderOld.getUser_id() + "取消订单,返还" + orderDetailsModel.getNum());
            publicStockService.addGoodsStock(addStockVo, orderOld.getUser_id());
            //扣减商品销量
//            productListModelMapper.updateProductListVolume(-orderDetailsModel.getNum(), vo.getStoreId(), integralGoodsModel.getGoods_id());

        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("秒杀关闭订单 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "cancleOrder");
        }
        return null;
    }

    @Override
    public Map<String, Object> loadMore(OrderVo vo) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> delOrder(OrderVo vo) {
        try {
            if (StringUtils.isEmpty(vo.getOrdervalue())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            String[] orderIds = vo.getOrdervalue().split(SplitUtils.DH);
            for (String orderId : orderIds) {
                OrderModel orderOld = new OrderModel();
                orderOld.setId(Integer.parseInt(orderId));
                orderOld.setStore_id(vo.getStoreId());
                orderOld.setOtype(DictionaryConst.OrdersType.ORDERS_HEADER_IN);
                orderOld.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS);
                orderOld = orderModelMapper.selectOne(orderOld);
                if (orderOld == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDBCZ, "订单不存在");
                }
                logger.debug("正在删除订单{}", orderOld.getsNo());
                //删除订单
                OrderModel orderUpdate = new OrderModel();
                orderUpdate.setId(orderOld.getId());
                orderUpdate.setRecycle(DictionaryConst.ProductRecycle.RECOVERY);
                int row = orderModelMapper.updateByPrimaryKeySelective(orderUpdate);
                if (row < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDGBSB, "订单关闭失败");
                }
                Map<String, Object> parmaMap = new HashMap<>(16);
                parmaMap.put("store_id", vo.getStoreId());
                parmaMap.put("orderno", orderOld.getsNo());
                parmaMap.put("recycle", DictionaryConst.ProductRecycle.NOT_STATUS);

                List<Map<String, Object>> orderDetailsModelList = orderDetailsModelMapper.getOrderDetailByGoodsInfo(parmaMap);
                for (Map<String, Object> detail : orderDetailsModelList) {
                    Integer status = MapUtils.getInteger(detail, "r_status");
                    int id = MapUtils.getIntValue(detail, "id");
                    int attrId = MapUtils.getIntValue(detail, "sid");
                    int goodsId = MapUtils.getIntValue(detail, "goodsId");
                    int pid = MapUtils.getIntValue(detail, "commodityId");
                    int num = MapUtils.getIntValue(detail, "num");
                    //删除明细
                    row = orderDetailsModelMapper.delOrderDetails1(vo.getStoreId(), DictionaryConst.ProductRecycle.RECOVERY, orderOld.getsNo());
                    if (row < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDGBSB, "订单关闭失败");
                    }
                    if (status.equals(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_COMPLETE) || status.equals(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_CLOSE)) {
                        logger.debug("订单明细id{} 状态{} 删除订单不回滚库存", id, status);
                        continue;
                    }
                    //回滚【积分】库存
                    integralGoodsModelMapper.releaseStockNum(orderOld.getsNo(), pid);
//                    //回滚商品库存
//                    AddStockVo addStockVo = new AddStockVo();
//                    addStockVo.setStoreId(vo.getStoreId());
//                    addStockVo.setId(attrId);
//                    addStockVo.setPid(goodsId);
//                    addStockVo.setAddNum(num);
//                    addStockVo.setText("后台删除订单,返还" + num);
//                    publicStockService.addGoodsStock(addStockVo, "admin");
                    //扣减商品销量
                    productListModelMapper.updateProductListVolume(-num, vo.getStoreId(), goodsId);
                }

            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("积分删除订单 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delOrder");
        }
        return null;
    }

    @Override
    public Map<String, Object> buyAgain(BuyAgainVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> orderSearch(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> delCart(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> getPaymentConf(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> orderDetails(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> showLogistics(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> cancleApply(int storeId, int id) {
        return null;
    }

    @Override
    public Map<String, Object> returnOrderList(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> okOrder(OrderVo orderVo) {
        return null;
    }

    @Override
    public Map<String, Object> returnMethod(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> seeSend(int stroeId, int productId) {
        return null;
    }

    @Override
    public Map<String, Object> backSend(ReturnGoodsVo returnGoodsVo) {
        return null;
    }

    @Override
    public Map<String, Object> seeExtractionCode(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> returndetails(RefundDetailsVo refundDetailsVo) {
        return null;
    }

    @Override
    public Map<String, Object> confirmReceipt(ReturnConfirmReceiptVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> cancelApplication(CancleAfterSaleApplyVo params) {
        return null;
    }

    @Override
    public Map<String, Object> getPayment(OrderVo vo) {
        return null;
    }
}

